package com.neuedu.web;

import com.alibaba.fastjson.JSON;
import com.neuedu.pojo.Userinfo;
import com.neuedu.service.UserinfoService;
import com.neuedu.service.UserinfoServiceImpl;
import com.neuedu.utils.UploadInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

@WebServlet(name = "UserUploadHeadServlet",urlPatterns = "/user/uploadHead")
@MultipartConfig
public class UserUploadHeadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 需要有上传图片的依赖
        // 在servlet上需要一个注解@MultipartConfig
        // 1.在服务器上保存图片 /xxxxx.jpg
        // 指定存储路径
        String savePath = getServletContext().getRealPath("/fly/res/images/avatar");
        File file = new File(savePath);
        if (!file.exists()){
            file.mkdirs();
        }
        // 获取上传的文件集合
        Collection<Part> parts = request.getParts();
        UUID uuid = null;
        String fileName = "";
        for (Part part : parts){
            String header = part.getHeader("content-disposition");
            // 获取文件名
            fileName = getFileName(header); // 1.jpg v JPG
            if (!fileName.endsWith(".jpg") && !fileName.endsWith(".JPG") && !fileName.endsWith(".png") && !fileName.endsWith(".PNG") && !fileName.endsWith(".gif") && !fileName.endsWith(".GIF")){
                UploadInfo uploadInfo = new UploadInfo();
                uploadInfo.setStatus(1);
                response.getWriter().println(JSON.toJSONString(uploadInfo));
                return;
            }
            // 把文件写到指定路径
            // 生成一个uuid
            uuid = UUID.randomUUID();
            part.write(savePath + File.separator + uuid + fileName);
        }
        // 2.修改数据库xxxxx.jpg
        UserinfoService userinfoService = new UserinfoServiceImpl();
        Userinfo login_user = (Userinfo) request.getSession().getAttribute("login_user");
        login_user.setHeadurl(uuid + fileName);
        int num = userinfoService.uploadHeadImg(login_user);
        // 3.同步更新session中login_user的headurl xxxxx.jpg
        // 4.响应ajax信息
        UploadInfo uploadInfo = new UploadInfo();
        uploadInfo.setStatus(0);
        uploadInfo.setPath(request.getContextPath()+"/fly/res/images/avatar" + uuid +fileName);
        response.getWriter().println(JSON.toJSONString(uploadInfo));
    }
    public String getFileName(String header){
        /**
         * String[] tempArr1 = header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
         * 火狐或者google浏览器下：tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
         * IE浏览器下：tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
         */
        String[] tempArr1 = header.split(";");
        /**
         * 火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
         * IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] tempArr2 = tempArr1[2].split("=");
        // 获取文件名，兼容各种浏览器的写法
        String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
        return fileName;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
